/*
 * igo: com.cctv.igo.admin.scheduler.service.TriggerService.java Create On 2011-5-3 下午11:21:58 By Q-Wang
 * $Revision: 1.2 $
 */
package com.ctvit.scheduler.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.ctvit.scheduler.common.SchedulerQueries;
import com.ctvit.scheduler.domain.QrtxTrigger;
import com.ctvit.scheduler.dto.Trigger;
import com.ctvit.framework.dao.Condition;
import com.ctvit.framework.dao.Pager;
import com.ctvit.framework.service.BaseService;
import com.ctvit.framework.web.context.ContextHolder;

/**
 * @author <a href="mailto:apeidou@gmail.com">Q-Wang</a>
 *
 */
public class TriggerService extends BaseService {

	private Condition createCondition(QrtxTrigger query) {
		Condition condition = new Condition();
		if (query!=null) {
			if (StringUtils.isNotEmpty(query.getType())) {
				condition.add("type",query.getType());
			}
			if (StringUtils.isNotEmpty(query.getName())) {
				condition.add("name",query.getName());
			}
		}
		return condition;
	}

	public void save(QrtxTrigger trigger) {
		trigger.setCreator(ContextHolder.getCurrentUser());
		trigger.setCreateTimestamp(new Date());
		genericDao.insert(trigger);
	}

	public Trigger get(Long id) {
		QrtxTrigger trigger = genericDao.getById(QrtxTrigger.class, id);
		if (trigger!=null) {
			return new Trigger(trigger);
		}
		return null;
	}

	public void update(QrtxTrigger trigger) {
		trigger.setModifier(ContextHolder.getCurrentUser());
		trigger.setModifyTimestamp(new Date());
		genericDao.updateExclusive(trigger, new String[]{"creator","createTimestamp"});
		// TODO Quartz 操作
	}

	public void delete(Long id, boolean cascade) {
		if (cascade) {
			genericDao.deleteBySqlID(SchedulerQueries.REMOVE_SCHEDULED_TASK_BY_TRIGGER, id);
		}
		genericDao.removeById(QrtxTrigger.class, id);
		// TODO Quartz 操作
	}

	public List<QrtxTrigger> list(QrtxTrigger query, int pageNo, int pageSize) {
		Condition condition = createCondition(query);
		return genericDao.getPagedByCondition(QrtxTrigger.class, condition, null, pageNo, pageSize);
	}

	public Pager<QrtxTrigger> list(Pager<QrtxTrigger> pager) {
		Condition condition = createCondition(pager.getQuery());
		List<QrtxTrigger> triggers = genericDao.getPagedByCondition(QrtxTrigger.class, condition, null, pager.getPageNo(), pager.getPageSize());
		long count = genericDao.getCountByCondition(QrtxTrigger.class, condition);
		pager.setResult(triggers);
		pager.setCount((int) count);
		return pager;
	}
}
